<?php

namespace App\Admin\Actions\Post;

use Encore\Admin\Actions\Action;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\InvoiceImport;
use Spatie\PdfToText\Pdf;
use App\Models\Invoice;
use Smalot\PdfParser\Parser;
use Illuminate\Support\Str;

class ImportInvoice extends Action
{
    public $name = '导入发票';

    protected $selector = '.import-post';

    public function handle(Request $request)
    {
        // 下面的代码获取到上传的文件，然后使用`maatwebsite/excel`等包来处理上传你的文件，保存到数据库
        

        header('Content-Type: text/html; charset=utf-8');

        $path1 = $request->file('file');

        $res = file_get_contents($path1);


        $parser = new Parser();


        $pdf = $parser->parseFile($path1);    //文件流
         
        $pdf = $pdf->getText();

        
        
       /*var_dump($text);
        if (strpos($text,"x00")) {

            echo "是";
        } else {
            echo "不是";
        }
        die;*/
        //$pdf = Pdf::getText($path1);

       /* $parser = new Parser();
        $pdf = $parser->parseFile($path1);

        //dd($pdf);
        $pages = $pdf->getPages();

        foreach ($pages as $page) {
            $text = $page->getText();
            dd($text);
        }*/


        if(!$pdf){

            return $this->response()->error('未抓取到内容');

        }

        $pdf = str_replace("\x00", "", $pdf);
        $pdf =htmlentities($pdf);
      
       /* $pdf = str_replace("\"", "", $pdf);

        $pdf = str_replace("\x19", "", $pdf);



        $pdf = str_replace("\x00", "", $pdf);
*/


      
        $content = [
            'model' => 'gpt-3.5-turbo',
            'messages' => [
                ['role' => 'system', "content"=> "你是个财务人员，根据下面内容分析出开票时间，开票主体和发票的总金额，返回格式用json返回，分别是开票主体，发票总金额，开票时间"],
                ['role' => 'user', 'content' => "'".$pdf."'"],
            ],
        ];

      
        
       

        $content = $this->curl($content);
        
        $content = json_decode($content,true);

       

        $gptContent = $content['choices'][0]['message']['content']; 
        
        $gptArr = json_decode($gptContent,true);
        
        
        $insertData['main'] = isset($gptArr['开票主体']) ? $gptArr['开票主体'] : '';
        $insertData['price'] = isset($gptArr['发票总金额']) ? $gptArr['发票总金额'] : '';
        $insertData['started_at'] = isset($gptArr['开票时间']) ? $gptArr['开票时间'] : '';


        Invoice::create($insertData);

       // Excel::import(new ResumeImport(), $path);

        return $this->response()->success('导入完成！')->refresh();
    }



   

    public function curl($data){

        $curl = curl_init();
        $data = json_encode($data);


        curl_setopt_array($curl, array(
           CURLOPT_URL => 'https://api.chatanywhere.tech/v1/chat/completions',
           CURLOPT_RETURNTRANSFER => true,
           CURLOPT_ENCODING => '',
           CURLOPT_MAXREDIRS => 10,
           CURLOPT_TIMEOUT => 0,
           CURLOPT_FOLLOWLOCATION => true,
           CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
           CURLOPT_CUSTOMREQUEST => 'POST',
           CURLOPT_POSTFIELDS =>$data,
           CURLOPT_HTTPHEADER => array(
              'Authorization: Bearer '.env('CHATGPT_API_KEY'),
              'User-Agent: Apifox/1.0.0 (https://apifox.com)',
              'Content-Type: application/json; charset=utf-8'
           ),
        ));

       $response = curl_exec($curl);

       //dd($response);
       return $response;
    }

    public function form()
    {
        $this->file('file', '请选择文件');
    }

    public function html()
    {
        return <<<HTML
        <a class="btn btn-sm btn-default import-post"><i class="fa fa-upload"></i>导入发票</a>
HTML;
    }
}